class WebSocketClient {
  constructor() {
    this.socketTask = null;
    this.isConnected = false;
    this.listeners = new Map();
  }

  async connect(roomId) {
    if (this.socketTask) {
      return;
    }

    const userInfo = uni.getStorageSync('userInfo');
    
    // 使用 uniCloud.connectWebSocket 方法连接
    this.socketTask = await uniCloud.connectWebSocket({
      name: "websocket",
      query: {
        roomId,
        openId: userInfo.openId
      }
    });

    this.socketTask.onOpen(() => {
      console.log('WebSocket连接已打开');
      this.isConnected = true;
    });

    this.socketTask.onMessage((res) => {
      try {
        const data = JSON.parse(res.data);
        this.notifyListeners(data);
      } catch (e) {
        console.error('解析WebSocket消息失败:', e);
      }
    });

    this.socketTask.onClose(() => {
      console.log('WebSocket连接已关闭');
      this.isConnected = false;
      this.socketTask = null;
    });

    this.socketTask.onError((error) => {
      console.error('WebSocket错误:', error);
      this.isConnected = false;
    });
  }

  addListener(event, callback) {
    if (!this.listeners.has(event)) {
      this.listeners.set(event, new Set());
    }
    this.listeners.get(event).add(callback);
  }

  removeListener(event, callback) {
    if (this.listeners.has(event)) {
      this.listeners.get(event).delete(callback);
    }
  }

  notifyListeners(data) {
    const { type, payload } = data;
    if (this.listeners.has(type)) {
      this.listeners.get(type).forEach(callback => callback(payload));
    }
  }

  send(data) {
    if (!this.isConnected) {
      console.warn('WebSocket未连接');
      return;
    }

    this.socketTask.send({
      data: JSON.stringify(data),
      fail: (error) => {
        console.error('发送消息失败:', error);
      }
    });
  }

  close() {
    if (this.socketTask) {
      this.socketTask.close();
      this.socketTask = null;
      this.isConnected = false;
    }
  }
}

export default new WebSocketClient(); 